// generated on 2016-11-30 using generator-webapp 2.3.2
const gulp = require('gulp');
const gulpLoadPlugins = require('gulp-load-plugins');
const browserSync = require('browser-sync').create();
const del = require('del');
const wiredep = require('wiredep').stream;
const runSequence = require('run-sequence');

const $ = gulpLoadPlugins();
const reload = browserSync.reload;
var dev = true;
const cdnBase = 'http://192.168.1.133:9001';

// var imageResize = require('gulp-image-resize');
// gulp.task('image-resize', function () {
//   gulp.src('app/img/*.jpg')
//     .pipe(imageResize({
//       width : 100,
//       height : 100,
//       crop : true,
//       upscale : false
//     }))
//     .pipe(gulp.dest('dist/img'));
// });



gulp.task('styles', () => {
  return gulp.src('app/css/*.css')
    .pipe($.plumber())
    .pipe($.sourcemaps.init())
    .pipe($.sass.sync({
      outputStyle: 'expanded',
      precision: 10,
      includePaths: ['.']
    }).on('error', $.sass.logError))
    .pipe($.autoprefixer({browsers: ['> 1%', 'last 2 versions', 'Firefox ESR']}))
    .pipe($.sourcemaps.write())
    .pipe(gulp.dest('.tmp'))
    .pipe(reload({stream: true}));
});

gulp.task('scripts', () => {
  return gulp.src('app/js/**/*.js')
    .pipe($.plumber())
    .pipe($.sourcemaps.init())
    // .pipe($.babel())
    .pipe($.sourcemaps.write('.'))
    .pipe(gulp.dest('.tmp'))
    .pipe(reload({stream: true}));
});

// function lint(files, options) {
//   return gulp.src(files)
//     .pipe($.eslint({ fix: true }))
//     .pipe(reload({stream: true, once: true}))
//     .pipe($.eslint.format())
//     .pipe($.if(!browserSync.active, $.eslint.failAfterError()));
// }

// gulp.task('lint', () => {
//   return lint('app/js/**/*.js')
//     .pipe(gulp.dest('app/js'));
// });
// gulp.task('lint:test', () => {
//   return lint('test/spec/**/*.js')
//     .pipe(gulp.dest('test/spec'));
// });

gulp.task('html', ['styles', 'scripts'], () => {
  return gulp.src('app/**/*.html')
    .pipe($.useref({searchPath: ['.tmp', 'app', '.']}))
    .pipe($.if('*.js', $.uglify()))
    .pipe($.if('*.css', $.cssnano({safe: true, autoprefixer: false})))
    // .pipe($.if('*.html', $.htmlmin({collapseWhitespace: true})))
    .pipe($.if('*.css', $.cdnify({
      base: cdnBase,
      rewriter: function(url, process) {
          return process(url).replace(/\\/g,'/');
      }
    })))               //添加cdn地址
    .pipe($.if('*.html', $.cdnify({
      html: {
        'link[rel="icon"]': 'href'
      },
      base: cdnBase,
      rewriter: function(url, process) {
        return process(url).replace(/\\/g,'/');
      }

    })))
    .pipe(gulp.dest('dist'));
});

gulp.task('images', () => {
  return gulp.src('app/img/**/*')
    .pipe($.cache($.imagemin()))
    .pipe(gulp.dest('dist/img'));
});

gulp.task('fonts', () => {
  return gulp.src(require('main-bower-files')('**/*.{eot,svg,ttf,woff,woff2}', function (err) {})
    .concat('app/fonts/**/*'))
    .pipe($.if(dev, gulp.dest('.tmp/fonts'), gulp.dest('dist/fonts')));
});

gulp.task('extras', () => {
  return gulp.src([
    'app/*',
    '!app/*.html'
  ], {
    dot: true
  }).pipe(gulp.dest('dist'));
});

gulp.task('clean', del.bind(null, ['.tmp', 'dist']));

gulp.task('serve', () => {
  runSequence(['wiredep'], ['styles', 'scripts', 'fonts'], () => {
    browserSync.init({
      notify: false,
      port: 9000,
      server: {
        baseDir: ['.tmp', 'app'],
        routes: {
          '/bower_components': 'bower_components'
        }
      }
    });

    gulp.watch([
      'app/**/*.html',
      'app/**/img/*',
      'app/**/*.js',
      'app/**/*.css',
      '.tmp/**/fonts/*'
    ]).on('change', reload);

    gulp.watch('app/**/*.css', ['styles']);
    gulp.watch('app/js/**/*.js', ['scripts']);
    gulp.watch('app/**/fonts/*', ['fonts']);
    gulp.watch('bower.json', ['wiredep', 'fonts']);
  });
});

gulp.task('serve:dist',  () => {
  browserSync.init({
    notify: false,
    port: 9001,
    server: {
      baseDir: ['dist']
    }
  });
});

gulp.task('serve:test', ['scripts'], () => {
  browserSync.init({
    notify: false,
    port: 9002,
    ui: false,
    server: {
      baseDir: 'test',
      routes: {
        '/js': '.tmp/js',
        '/bower_components': 'bower_components'
      }
    }
  });

  gulp.watch('app/js/**/*.js', ['scripts']);
  gulp.watch(['test/spec/**/*.js', 'test/index.html']).on('change', reload);
  gulp.watch('test/spec/**/*.js', ['lint:test']);
});

// inject bower components
gulp.task('wiredep', () => {
  gulp.src('app/css/*.css')
    .pipe($.filter(file => file.stat && file.stat.size))
    .pipe(wiredep({
      ignorePath: /^(\.\.\/)+/
    }))
    .pipe(gulp.dest('app/css'));

  gulp.src('app/**/*.html')
    .pipe(wiredep({
      // exclude: ['bootstrap-sass'],
      ignorePath: /^(\.\.\/)*\.\./
    }))
    .pipe(gulp.dest('app'));
});

gulp.task('build', ['html', 'images', 'fonts', 'extras'], () => {
  return gulp.src('dist/**/*').pipe($.size({title: 'build', gzip: true}));
});

gulp.task('default', () => {
  return new Promise(resolve => {
    dev = false;
    runSequence(['clean', 'wiredep'], 'build', resolve);
  });
});
